package net.adetech.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.im4java.core.ConvertCmd;
import org.im4java.core.IM4JavaException;
import org.im4java.core.IMOperation;
import org.im4java.core.IdentifyCmd;
import org.im4java.process.ArrayListOutputConsumer;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

/**
 * Created by sunfeihu on 2016/11/9.
 * 使用graphicsmagick 以及 im4java 进行图片处理
 */
public class UtilsImage {

    /**
     * 等比例缩放图片
     *
     * @param f          原始文件
     * @param maxSize    长或者宽的最大尺寸
     * @param folderName 在当前缩放文件路径下创建的另外存储文件夹
     * @return 修改后的文件相对路径
     */
    public static void resize(File f, int maxSize, String folderName) {
        String outName = "";
        File outFile = f;
        if (null != folderName) {
            File newFolder = new File(f.getParentFile(), folderName);
            if (!newFolder.exists()) {
                newFolder.mkdir();
            }
            String fileName = FilenameUtils.getName(f.getAbsolutePath());
            outFile = new File(newFolder, fileName);
        }
        try {
            IMOperation op = new IMOperation();
            op.addImage(f.getAbsolutePath());
            op.resize(maxSize);
            op.addImage(outFile.getAbsolutePath());
            ConvertCmd cmd = new ConvertCmd(true);
            String osName = System.getProperty("os.name").toLowerCase();
            if (osName.indexOf("win") >= 0) {  //linux下不要设置此值，不然会报错
                cmd.setSearchPath(UtilsProperties.getInstance().getProperty("graphicsMagick.path"));
            }
            cmd.run(op);
        } catch (IM4JavaException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 等比例缩放图片
     *
     * @param f       原始文件
     * @param maxSize 长或者宽的最大尺寸
     */
    public static void resize(File f, int maxSize) {
        resize(f, maxSize, null);
    }

    /**
     * 获取图片文件的基本信息
     *
     * @param f 图片文件
     * @return 基本信息存储在JSONObject中
     */
    public static JSONObject getInfo(File f) {
        JSONObject obj = null;
        try {
            IMOperation op = new IMOperation();
            op.format("{width:%w,height:%h,size:'%b'}"); // 设置获取宽度参数
            op.addImage(1);
            IdentifyCmd cmd = new IdentifyCmd(true);
            String osName = System.getProperty("os.name").toLowerCase();
            if (osName.indexOf("win") >= 0) {  //linux下不要设置此值，不然会报错
                cmd.setSearchPath(UtilsProperties.getInstance().getProperty("graphicsMagick.path"));
            }
            ArrayListOutputConsumer output = new ArrayListOutputConsumer();
            cmd.setOutputConsumer(output);
            cmd.run(op, f.getAbsolutePath());
            ArrayList<String> cmdOutput = output.getOutput();
            assert cmdOutput.size() == 1;
            obj = JSONObject.parseObject(cmdOutput.get(0));
            String sizeStr = obj.getString("size");
            //如果是KB结束
            if (sizeStr.endsWith("Ki")) {
                long size = Math.round((NumberUtils.createDouble(sizeStr.substring(0, sizeStr.length() - 2)) * 1024D));
                obj.put("size", size);
            } else if (sizeStr.endsWith("Mi")) {
                long size = Math.round((NumberUtils.createDouble(sizeStr.substring(0, sizeStr.length() - 2)) * 1024D * 1024D));
                obj.put("size", size);
            }
        } catch (IM4JavaException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return obj;
    }

}